<template>
  <!-- 新增安全培训记录 -->
  <view class="newFireProtection">
    <view class="wrapper">
      <view class="wrapper-item content">
        <u-form :model="form" ref="form" label-width="100" labelPosition="’top‘" :error-type="errorType">
          <u-form-item label="培训主题" :borderBottom="false" :required="true">
            <u--input v-model.trim="form.trainingTheme" border="none" placeholder="请填写培训主题" :maxlength="30"></u--input>
          </u-form-item>

          <u-form-item label="培训地点" :borderBottom="false" :required="true">
            <u--input v-model.trim="form.trainingPlace" border="none" placeholder="填写培训地点" :maxlength="30"></u--input>
          </u-form-item>

          <u-form-item label="培训时间" :borderBottom="false" :required="true" @click="cellTimeClick('trainingTime')">
            <u--input v-model="form.trainingTimeName" disabled disabledColor="#ffffff" placeholder="请选择"
              border="none"></u--input>
            <image :src="baseImgUrl + 'day-icon2.png'" mode="" slot="right" class="seleTime"></image>
          </u-form-item>

          <u-form-item label="参训人员" :borderBottom="false" :required="true">
            <u--input v-model.trim="form.trainingPerson" border="none" placeholder="填写此次参加培训的人员分类，例：全部人员"
              :maxlength="30"></u--input>
          </u-form-item>

          <view style="padding-top: 20rpx"></view>
          <view class="forTitle">
            <view> <text class="forReq">*</text>培训内容 </view>
          </view>
          <view class="text-AreaView">
            <u--textarea v-model="trainingContent" placeholder="请简要填写本次培训的主要内容，字数在1000字以内" count maxlength="1000"
              height="260"></u--textarea>
          </view>

          <view style="padding-top: 20rpx"></view>
          <view class="forTitle">
            <view> <text class="forReq">*</text>培训现场图片 </view>
            <view class="state">（上传1-3张图片）</view>
          </view>
          <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="3"
            :multiple="true" width="96" height="80">
            <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
          </u-upload>
        </u-form>
      </view>
    </view>

    <view class="btns thispageBtn">
      <button class="cancel-btn lt" type="primary" @click="navBack()">
        取消
      </button>
      <button class="submit-btn" type="primary" @click="submitHandle">
        保存
      </button>
    </view>

    <!-- 时间选择器 -->
    <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="datetime"
      :formatter="formatter" :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose" @cancel="pickerTimeClose(1)"
      @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
  </view>
</template>

<script>
  import {
    fireTrainingSave
  } from "@/api/myself.js";
  import {
    Toast,
    navBack,
    handleClickRouter,
    uniTrim,
    pvwImage,
    useNetWork,
    isLoading,
    formatters,
    dayTurnTime,
    getHeader,
    uploadFile,
  } from "@/utils/util.js";
  import moment from "@/utils/moment.js";
  import mixin from "@/utils/mixin.js";

  export default {
    name: "newFireProtection",
    mixins: [mixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        options: {},
        form: {},
        errorType: ["none"],
        trainingContent: "",
        fileList: [],
        fireTrainingImagesUrlList: [],
        fileNum: 0, // 记录长传图片张数
      };
    },
    onLoad(options) {
      this.options = options;
      this.form.trainingTimeName = moment().format("YYYY/MM/DD HH:mm");
      this.form.trainingTime = moment().valueOf();
    },
    methods: {
      handleClickRouter,
      navBack,
      pvwImage,
      moment,
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick(e) {
        this.cellType = e;
        var minDateNum = +new Date(); //获取当前时间的毫秒数

        switch (this.cellType) {
          case "trainingTime":
            this.maxDate = minDateNum;
            this.timeValue = this.maxDate;
            break;
          default:
            break;
        }

        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },
      pickerTimeClose(e) {
        if (e) {
          switch (this.cellType) {
            case "trainingTime":
              this.form.trainingTime = "";
              this.form.trainingTimeName = "";
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          switch (this.cellType) {
            case "trainingTime":
              this.form.trainingTimeName = formatters(arr, "YY/MM/DD HH:mm");
              this.form.trainingTime = dayTurnTime(this.form.trainingTimeName);
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      afterRead(info) {
        useNetWork(); // 判断是否有网络
        isLoading();

        let _this = this;
        _this.fileNum += info.file.length;
        for (let v of info.file) {
          uploadFile({
              url: "/web/sys/upload/upload_file",
              filePath: v.url,
              name: "file",
              formData: {
                type: 48,
              },
            })
            .then((res) => {
              let {
                fullPath,
                halfPath
              } = res.result;
              this.fileList.push({
                url: fullPath
              });
              this.fireTrainingImagesUrlList.push(halfPath);
              if (this.fireTrainingImagesUrlList.length == this.fileNum) {
                isLoading(false);
              }
            })
            .finally((err) => {
              isLoading(false);
            })
        }
      },
      deletePic(e) {
        this.fileList.splice(e.index, 1);
        this.fireTrainingImagesUrlList.splice(e.index, 1);
        this.fileNum -= 1;
      },
      submitHandle() {
        let {
          trainingTheme,
          trainingPlace,
          trainingTime,
          trainingPerson,
          neibuzhaop,
        } = this.form;

        if (!trainingTheme || !uniTrim(trainingTheme)) {
          Toast("请输入培训主题");
          return;
        }

        // let companyRegular = /^[a-zA-Z\u4e00-\u9fa5]+$/;
        // if (!companyRegular.test(trainingTheme)) {
        //   Toast("请输入正确的培训主题");
        //   return;
        // }

        if (!trainingPlace || !uniTrim(trainingPlace)) {
          Toast("请输入培训地点");
          return;
        }

        if (!trainingTime) {
          Toast("请选择培训时间");
          return;
        }

        if (!trainingPerson) {
          Toast("请输入参训人员");
          return;
        }

        if (!this.trainingContent) {
          Toast("请输入培训内容");
          return;
        }

        if (!this.fileList.length) {
          Toast("请上传培训现场图片");
          return;
        }

        let data = {
          companyId: this.options.companyId,
          trainingTheme,
          trainingPlace,
          trainingTime,
          trainingPerson,
          trainingContent: this.trainingContent,
          fireTrainingImagesUrlList: this.fireTrainingImagesUrlList,
        };

        fireTrainingSave(data).then((res) => {
          if (res.code == 200) {
            Toast("保存成功");
            uni.setStorageSync("fireDrill", true);
            navBack();
            return;
          }
          Toast(res.message);
        });
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  .newFireProtection {
    flex: 1;
    background-color: #f3f3f3;

    .newFireProtection-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 30rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 710rpx;
      }

      .content {
        margin: 0 auto;
        height: calc(100vh - 90px);
        overflow-y: auto;
      }

      /deep/.u-form-item__body__right__content {
        padding: 12rpx 18rpx;
        border-radius: 8rrpx;
        background: #f9f9f9;
      }

      /deep/.u-input__content {
        background: #f9f9f9;
      }

      .seleTime {
        width: 30rpx;
        height: 30rpx;
      }

      .forTitle {
        display: flex;
        position: relative;
        margin-bottom: 15rpx;
        font-size: 30rpx;

        .forReq {
          position: absolute;
          left: -9px;
          color: #f56c6c;
          line-height: 20px;
          font-size: 20px;
          top: 3px;
        }

        .state {
          color: #a1a1a1;
          font-size: 26rpx;
        }
      }

      .text-AreaView {

        /deep/.u-textarea,
        .u-textarea__count {
          background-color: #f9f9f9 !important;
        }

        .u-textarea__field {
          font-weight: 400;
        }

        /deep/.input-placeholder {
          font-weight: 400;
        }
      }
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }
  }
</style>